﻿using System;
using RpcHelper;
using RpcModel;
using RpcModularModel.Shield;
using Wedonek.RpcStore.Service.DAL;
using Wedonek.RpcStore.Service.Interface;
using Wedonek.RpcStore.Service.Model;

namespace Wedonek.RpcStore.Service.Collect
{
    internal class ResourceShieldCollect : BasicCollect<ResourceShieldDAL>, IResourceShieldCollect
    {
        public long Add(ResourceShield shield)
        {
            if (base.BasicDAL.CheckIsShieId(shield.ShieKey, shield.ResourcePath))
            {
                throw new ErrorException("rpc.shieId.repeat");
            }
            long id = base.BasicDAL.Add(shield);
            this._SyncShieId(shield);
            return id;
        }
        public ResourceShield Get(Guid resourceId)
        {
            ResourceShield shield = base.BasicDAL.Get(resourceId);
            if (shield == null)
            {
                throw new ErrorException("rpc.shieId.not.find");
            }
            return shield;
        }
        public void SetBeOverdueTime(ResourceShield shield, DateTime? beOverdueTime)
        {
            long time = beOverdueTime.HasValue ? beOverdueTime.Value.ToLong() : 0;
            if (shield.BeOverdueTime == time)
            {
                return;
            }
            base.BasicDAL.SetBeOverdueTime(shield.Id, time);
            this._SyncShieId(shield);
        }
        public Guid[] CheckIsShieId(Guid[] resourceId)
        {
            return base.BasicDAL.CheckIsShieId(resourceId);
        }
        private void _SyncShieId(ResourceShield shield)
        {
            new SyncShieId
            {
                ServerId = shield.ServerId,
                SystemType = shield.SystemType,
                Path = shield.ResourcePath,
                RpcMerId = shield.RpcMerId,
                VerNum = shield.ApiVerNum
            }.Send(shield.RpcMerId, 0);
        }
        public ResourceShield Get(long id)
        {
            ResourceShield shield = base.BasicDAL.Get(id);
            if (shield == null)
            {
                throw new ErrorException("rpc.store.shieId.not.find");
            }
            return shield;
        }

        public void Delete(ResourceShield shield)
        {
            base.BasicDAL.Delete(shield.Id);
            this._SyncShieId(shield);
        }

        public ResourceShield[] Query(ShieIdQueryParam query, IBasicPage paging, out long count)
        {
            return base.BasicDAL.Query(query, paging, out count);
        }
    }
}
